package com.hzx.demo.helper;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.os.Process;
import android.widget.Toast;

import com.hzx.demo.util.HZXLog;

/**
 * 仿照Acra实现的原理监听所有异常
 *  当然实现还是有很大区别的，　
 * Created by ke on 16-5-18.
 */
public class ErrorReporter implements Thread.UncaughtExceptionHandler{
    @SuppressWarnings("unused")
    private static final String TAG = "ErrorReporter";
    private Context mContext;

    /**
     * This method must be called in main thread
     */
    public ErrorReporter(Context context){
        if(Looper.getMainLooper().getThread() != Thread.currentThread()){
            throw new IllegalStateException("ErroReporter constructor must be called in main thread");
        }
        mContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        HZXLog.e(TAG, "uncaughtException,excption is" + ex.getMessage(), ex);
        HZXLog.e(TAG, "current Thread is %s", thread);
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        mContext.startActivity(intent);
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                LogCatCollector logCatCollector = new LogCatCollector();
                String result = logCatCollector.collectLog();
                Toast.makeText(mContext, "Hello", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            // none
        }
        Process.killProcess(Process.myPid());
        System.exit(10);
    }
}
